﻿using DocumentFormat.OpenXml.Office2010.Excel;
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NP.BPMReportPlatform.Cadre.Dto;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Performance;
using NP.BPMReportPlatform.RecurringJobs;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using static NP.BPMReportPlatform.Performance.Dto.PerformanceDto;
using static NP.BPMReportPlatform.RecurringJobs.Dto.SFPerformDto;

namespace NP.BPMReportPlatform.UserTrial
{
    /// <summary>
    /// 员工绩效接口
    /// </summary>
    [Authorize]
    [ApiController]
    [Route("api/performance")]
    public class PerformanceController : BPMReportPlatformController
    {
        private readonly IPerformanceService _performanceService;
        private readonly ISFPerformanceSyncJob _performanceJobService;

        public PerformanceController(IPerformanceService performanceService, ISFPerformanceSyncJob performanceJobService)
        {
            _performanceService = performanceService;
            _performanceJobService = performanceJobService;
        }

        /// <summary>
        /// 绩效待办查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPerformanceResultAsync")]
        public async Task<PagedResultDto<GetPerformanceResultOutput>> GetPerformanceToDo([FromBody] GetPerformanceResultInput input)
        {
            return await _performanceService.GetPerformanceToDo(input);
        }

        /// <summary>
        /// 绩效待办导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExportPerformanceResultAsync")]
        public async Task<XlsxFileResult<ExportPerformanceOutput>> ExportResultListAsync([FromBody] GetPerformanceResultInput input)
        {
            input.PageSize = int.MaxValue;
            var rst = (await _performanceService.GetPerformanceToDo(input)).Items.ToList();
            var result = rst.Adapt<List<ExportPerformanceOutput>>();
            return new XlsxFileResult<ExportPerformanceOutput>(result, "绩效待办列表导出");
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <param name="entity">数据</param>
        [HttpPost]
        [Route("Submit")]
        public Task<string> Submit([FromBody] SubmitScopeDto entity)
        {
            return _performanceService.Submit(entity);
        }

        /// <summary>
        /// 获取表单明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Detail")]
        public async Task<object> GetDetailById([FromQuery] int id)
        {
            return await _performanceService.GetDetailById(id);
        }

        /// <summary>
        /// 检查待办状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckTodoById")]
        public async Task<bool> CheckToDoData([FromQuery] int id)
        {
            return await _performanceService.CheckToDoData(id);
        }

        /// <summary>
        /// 根据工号获取历史绩效信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetHistoryData")]
        public async Task<List<SFHistoryResponse.SFHistoryData>> GetHistoryData([FromBody] GetPerformanceResultInput input)
        {
            return await _performanceJobService.GetHistoryData(input.KeyWord);
        }

        /// <summary>
        /// 催办
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Urging")]
        public async Task<string> Urging([FromQuery] string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var ids = id.Split(',').Select(t => int.Parse(t)).ToList();
                _performanceJobService.SendEmail(ids);
            }

            return "已催办";
        }

        /// <summary>
        /// 根据工号获取历史绩效信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetHistoryDataDetail")]
        public async Task<PerformHistoryDto> GetHistoryDataDetail([FromQuery] string userid, [FromQuery] int id)
        {
            return await _performanceJobService.GetHistoryDataDetail(userid, id);
        }

        /// <summary>
        /// 单个数据导出
        /// </summary>
        /// <param name="requestdata"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExportResultDetailAsync")]
        public async Task<FileResult> ExportResultDetailAsync([FromBody] PerformHistoryExportStringDto requestdata)
        {
            PerformHistoryExportDto data = JsonConvert.DeserializeObject<PerformHistoryExportDto>(requestdata.requestdata);
            var rst = await _performanceService.ExportResultDetailAsync(data);
            string downloadFileName = System.Guid.NewGuid().ToString("N") + ".xlsx";
            rst.Close();
            return File(rst.ToArray(), "application/octet-stream", $"{downloadFileName}.xlsx");
        }

        private byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    }
}